$(function() {

    let layer = layui.layer
    let form = layui.form

    var laypage = layui.laypage;

    let q = {
        pagenum: 1, //默认在第一页
        pagesize: 2, //每页显示两行
        cate_id: '', //分类的id
        state: '' //文章状态
    }

    initTable() //获取数据渲染

    initCate()

    // 获取列表数据
    function initTable() {
        $.ajax({
            method: 'GET',
            url: '/my/article/list',
            data: q,
            success: function(res) {
                if (res.status !== 0) return layer.msg('获取文章失败')

                let htmlstr = template('tpl_table', res)
                $('tbody').html(htmlstr)

                renderPage(res.total)
            }
        })
    }

    //获取时间
    template.defaults.imports.dataFormat = function(date) {
        let dt = new Date(date)

        let y = dt.getFullYear() //年
        let m = dt.getMonth() + 1 //月
        let d = dt.getDate() //日

        let hh = dt.getHours() //时
        let mm = dt.getMinutes() //分
        let ss = dt.getSeconds() //秒

        return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
    }

    //渲染下拉菜单
    function initCate() {
        $.ajax({
            method: 'GET',
            url: '/my/article/cates',
            success: function(res) {
                if (res.status !== 0) {
                    layer.msg('获取分类数据失败')
                }
                let htmlstr = template('tpl-cate', res)
                $('[name=cate_id]').html(htmlstr)
                form.render() //重新渲染表单结构
            }
        })
    }

    //筛选
    $('#form-search').on('submit', function(e) {
        e.preventDefault()
        let cate_id = $('[name=cate_id]').val()
        let state = $('[name=state]').val()

        q.state = state
        q.cate_id = cate_id

        initTable()
    })

    //分页渲染
    function renderPage(total) {
        laypage.render({
            elem: 'pageBox',
            count: total,
            limit: q.pagesize,
            curr: q.pagenum,
            limits: [2, 3, 5, 10],
            layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
            jump: function(obj, first) {
                q.pagenum = obj.curr
                q.pagesize = obj.limit

                if (!first) {
                    initTable()
                }
            }
        })
    }

    // 删除按钮
    $('body').on('click', '.btn-delete', function() {
        let id = $(this).attr('data-id')
        console.log(id)
        layer.confirm('确认删除?', { icon: 3, title: '提示' }, function(index) {

            $.ajax({
                method: 'GET',
                url: '/my/article/delete/' + id,
                success: function(res) {
                    if (res.status !== 0) return layer.msg('删除文章失败')
                    layer.msg('删除文章成功')
                    initTable()
                }
            })
        })
    })

})